<?php
declare(strict_types=1);

namespace App\AdminApi\Module\User\Api;

use App\AdminApi\AdminApiBasicsController;
use App\AdminApi\Module\User\Seaech\UserSearch;
use App\AdminApi\Module\User\Service\UserService;
use App\AdminApi\Module\User\Validate\UserValidate;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;
use Zms\AdminElementPlus\FormCreate\ElemenuForm;
use Zms\Guard\Auth;
use Zms\HyperfResponse\Response;
use Zms\HyperfValidateAnnotations\Validate;
use Zms\Validate\Type;

#[
    Auth(guard: self::GUARD, label: ['用户管理', '用户管理'], app: self::APP),
    Controller(prefix: "/admin-api/user", server: self::SERVER)
]
class UserController extends AdminApiBasicsController
{
    #[Inject]
    protected UserService $user;
    #[
        GetMapping('lists'),
        Auth(sign: 'user.lists')
    ]
    public function lists(): ResponseInterface
    {
        $search = new UserSearch([
            'where' => $this->query(),
            'page' => $this->page(),
            'size' => $this->pageSize(),
            'order' => $this->orderBy()
        ]);
        return Response::Api()->success(
            data: $search->search()
        );
    }

    #[
        GetMapping('detail'),
        Auth(label: ['会员详情'], sign: 'user.detail')
    ]
    public function detail(): ResponseInterface
    {
        $id = (int)$this->request->input('id');
        return Response::Api()->success(
            data: $this->user->getUserDetail(['id' => $id])
        );
    }


    #[
        PostMapping('status'),
        Auth(sign: "user.status", logger: false, describe: '更改会员状态'),
        Validate(rules: \Zms\Constants\Validate::CHANGE_STATUS_RULES)
    ]
    public function status(): ResponseInterface
    {
        $data = $this->request->inputs(['id', 'status']);
        if ($this->user->search(['id' => $data['id']])->update(['status' => $data['status']])) {
            return Response::Api()->success('更改成功');
        }
        return Response::Api()->fail('更改失败');
    }


    #[
        RequestMapping('created'),
        Auth(sign: 'user.created', logger: "POST"),
        ElemenuForm(UserService::class, 'userForm'),
        Validate(class: UserValidate::class, scene: 'created')
    ]
    public function created(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->user->saveUserData($data)) {
            return Response::Api()->success('会员创建成功');
        }
        return Response::Api()->fail('会员创建失败');
    }


    #[
        RequestMapping('updated'),
        Auth(sign: 'user.updated', logger: "POST"),
        ElemenuForm(UserService::class, 'userForm', param: ['id']),
        Validate(class: UserValidate::class, scene: 'updated')
    ]
    public function updated(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->user->saveUserData($data)) {
            return Response::Api()->success('会员编辑成功');
        }
        return Response::Api()->fail('会员编辑失败');
    }


    #[
        RequestMapping('updated-field'),
        Auth(label: ['编辑用户信息'], relyon: ['user.updated'], logger: "POST", describe: '会员单独数据编辑'),
        ElemenuForm(UserService::class, 'userForm', param: ['id', 'field'])
    ]
    public function UpdatedField(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        $field = $data['field'] ?? '';
        if (!$field) {
            return Response::Api()->fail("编辑失败,参数错误");
        }
        if (!($this->user->hasField($field) && $field !== 'id')) {
            return Response::Api()->fail("编辑失败,要修改的字段无效");
        }
        $validate = (new UserValidate())->setFields(['id', $field])->setData($data)->validate();
        if ($validate->isFail()) {
            return Response::Api()->fail($validate->firstError());
        }
        if ($this->user->saveUserData($validate->getSafeData())) {
            return Response::Api()->success('会员编辑成功');
        }
        return Response::Api()->fail('会员编辑失败');
    }


    #[
        RequestMapping('deleted'),
        Auth(sign: 'user.deleted', logger: "POST"),
        Validate(rules: [
            ['id', Type::REQUIRED_CHOOSE, 'error' => '请选择要删除的会员']
        ])
    ]
    public function deleted(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->user->deletedUser((int)$data['id'])) {
            return Response::Api()->success('会员删除成功');
        }
        return Response::Api()->fail('会员删除失败');
    }


    #[
        RequestMapping('recycle'),
        Auth(label: ['恢复'], sign: 'user.recycle', logger: "POST"),
        Validate(rules: [
            ['id', Type::REQUIRED_CHOOSE, 'error' => '请选择要恢复的会员']
        ])
    ]
    public function recycle(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->user->recycleUser((int)$data['id'])) {
            return Response::Api()->success('会员恢复成功');
        }
        return Response::Api()->fail('会员恢复失败');
    }
}